<?php

if (!defined('MOODLE_INTERNAL')) {
	die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
}

$CFG->gwtmodule = "mercurius.fitness.Fitness";  

require_once ($CFG->dirroot . '/mercurius/lib.php');


/// Check if Moodle is properly installed.
if (!$site = get_site()) {
	redirect("site.php");
}

$feedkey = optional_param('feedkey');
$adminfeedkey = optional_param('adminfeedkey');
$rowlimit = optional_param('rowlimit');
$loggerlevel = optional_param('loggerlevel');
$google_api_key = optional_param('google_api_key');
$keyaccess = false;

if(!empty ($feedkey) or !empty ($adminfeedkey)) {
	$keyaccess = true;
}

if (!$keyaccess) {
	require_login();
} else if($keyaccess){
	
	if(!record_exists('mercurius','name',"version")) {
		print_header_simple("",'heading', 'home');
		error("Mercurius is not configured yet to be used with feedkeys.  Contact your administrator");
	}
	
	if(!empty($feedkey)) {
		$USER = get_user_from_feed_key($feedkey);
		$USER->adminfeed_key = ""; // to prevent somebody accessing admin stuff from reg. feed key
	}
	
	// Always make adminfeedkey take preference, so run after feedkey
	if (!empty ($adminfeedkey)) {
		$USER = get_user_from_adminfeed_key($adminfeedkey);
		$feedkey = $USER->feed_key;
	}	
}

if (empty ($USER) or $USER->id == 0) {
	require_login();
} else if(!$keyaccess) {
	$USER =  get_mercurius_user($USER);
}

$courseid = optional_param('course', 0, PARAM_INT);

if (empty ($courseid)) {
	$courseid = $site->id;
}

$course = get_record("course", "id", $courseid);

$stradministration = get_string("administration");
$strmercurius = get_string('mercurius', 'mercurius');

// Check if tables exists


if (!$tables = $db->Metatables()) {
	header('Location: '.$CFG->wwwroot . '/index.php');
} else {

	$mercuriustables = true;
	$mercuriustbls = array (
		"mercurius",
		"mercurius_exercise_log",
		"mercurius_user_settings",
		"mercurius_measurement_log",
		"mercurius_exercise_data"
	);

	foreach ($mercuriustbls as $mercuriustbl) {
		if (!in_array($CFG->prefix . $mercuriustbl, $tables)) {
			$mercuriustables = false;
		}
	}

	if (!$mercuriustables) {
		$strdatabasesuccess = get_string("databasesuccess");


		if (file_exists($CFG->libdir . '/dmllib.php') && file_exists($CFG->libdir . '/ddllib.php') && file_exists($CFG->dirroot . '/mercurius/db/install.xml')) {
			require_once($CFG->libdir .'/ddllib.php');
			$db->debug = true;
			if (!install_from_xmldb_file($CFG->dirroot . '/mercurius/db/install.xml')) {
				print_header_simple("",'heading', 'home');
				error("Error while installing mercurius plugin (XML)!");
			}
			$db->debug = false;
			notify($strdatabasesuccess, "green");
			include_once ($CFG->dirroot . '/mercurius/version.php');
			$mercurius = new stdClass();
			$mercurius->name = 'version';
			$mercurius->value = $mercuriusversion;
			if (!insert_record('mercurius', $mercurius)) {
				error('Could not write version information to database');
			}
			$mercurius->name = 'release';
			$mercurius->value = $mercuriusrelease;
			if (!insert_record('mercurius', $mercurius)) {
				print_header_simple("",'heading', 'home');
				error('Could not write release information to database');
			}
		}

		redirect("$CFG->wwwroot/mercurius/", $strdatabasesuccess, 1);
		exit;

	}

	// Get mercurius version
	include_once ($CFG->dirroot . '/mercurius/version.php');
	$dbversion = @ get_field("mercurius", "value", "name", "version");
	$dbversion = (int) $dbversion;

	if (empty ($dbversion) or ($dbversion < $mercuriusversion)) {
		if (file_exists($CFG->dirroot . '/mercurius/db/upgrade.php')) {
			include_once ($CFG->dirroot . '/mercurius/db/upgrade.php');
			$upgradefunc = 'xmldb_mercurius_upgrade';
		}

		print_header("$site->shortname: $stradministration", "$site->fullname", " $strmercurius");

		if ($upgradefunc ($dbversion)) {
			set_field("mercurius", "value", $mercuriusversion, "name", "version");
			set_field("mercurius", "value", $mercuriusrelease, "name", "release");
			notify(get_string('databaseupdated', 'mercurius', $mercuriusversion), 'green');
		}

		print_continue("index.php?course=$courseid&amp;sesskey=$USER->sesskey");
		print_footer();
		exit;

	}
}


$api = get_field("mercurius", "value", "name", "google_api_key");

if(isadmin() and !empty($google_api_key)) {
	$api = get_field("mercurius", "value", "name", "google_api_key");
	if(!empty($api)) {
		// It's already set
		set_field("mercurius", "value", $google_api_key, "name", "google_api_key");
	} else {
		$do = new stdClass();
		$do->name = 'google_api_key';
		$do->value = $google_api_key;
		insert_record('mercurius', $do);
	}
	
	// Lets double check
	$api = get_field("mercurius", "value", "name", "google_api_key");
	
	print_header_simple("",'heading', 'home');
	if(empty($api)) {
		error('Could not set Google GMap API Key: ' . $google_api_key);
	} else {
		notice ('Google GMap API Key set', $CFG->wwwroot . '/mercurius/index.php');
	}
	print_footer();
} else if(isadmin() and empty($api)) {
	print_header_simple("",'heading', 'Mercurius');
	print_simple_box_start('center');
	print_heading("Mercurius not fully configured");
	print_heading("Enter Google Map API Key");
	echo '<center>';
	echo '<form action="index.php" method="post">';
    echo '<input type="text" name="google_api_key" value="" />';
    echo '<input type="hidden" name="sesskey" value="' . $USER->sesskey . '" />';
    echo '<br/>';
    echo '<br/>';
    echo '<input type="submit" value="' . get_string('savechanges','admin') . '" />';
    echo '</form>';
    echo '</center>';
    print_simple_box_end();
    print_footer();
   
	exit;
} else if(empty($api)) {
	print_header_simple("",'heading', 'Mercurius');
	error("Mercurius is not fully configured.  Consult the administrator.");
}

$usersettings = (array) get_record("mercurius_user_settings", "userid", $USER->id);

$action = optional_param('action');
$initwindow = optional_param('initwindow');

$vars = "var serviceurl = \"{$CFG->wwwroot}/mercurius/{$CFG->gwtmodule}/index.php\";";
$variables = "var variables =  {";

if(!empty($adminfeedkey)) {
	$variables .= "adminfeedkey: adminfeedkey,";
	$vars .= "var adminfeedkey = \"$adminfeedkey\";";
}

if(!empty($feedkey)) {
	$variables .= "feedkey: feedkey,";
	$vars .= "var feedkey = \"$feedkey\";";
}

if(!empty($rowlimit)) {
	$variables .= "rowlimit: rowlimit,";
	$vars .= "var rowlimit = \"$rowlimit\";";
}

if(!empty($loggerlevel)) {
	$variables .= "loggerlevel: loggerlevel,";
	$vars .= "var loggerlevel = \"$loggerlevel\";";
}

if(count($usersettings) == 1) {
	$variables .= "settings: 0,";
}

if (isset($CFG->enablerssfeeds) && $CFG->enablerssfeeds) {
	$variables .= "rss: 1,";
}

if(!empty($initwindow)) {
	$variables .= "initwindow: initwindow,";
	$vars .= "var initwindow = \"$initwindow\";";
}


   $variables .= "serviceurl: serviceurl,".
    "userid: {$USER->id}".
  	"};";
  
$variables = $vars . $variables;

$meta = "<meta name=\"gwt:module\" content=\"{$CFG->gwtmodule}\" />";
$bodyvalues = 'leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"';
$title = "Mercurius";

if(isset($generic_page) and $generic_page) {
	
} else if (empty ($action)) {

	$CFG->javascript = $CFG->dirroot . '/mercurius/empty.php';
	print_header_simple($title,'heading', 'Mercurius', '',$meta,true,'&nbsp;','',false,$bodyvalues);
	include('../html/gwtbody.html');
	print_footer();
} else if($action == 'showMercurius' or $action == 'showGWT') {
	echo "<html><head>";
	echo $meta;
	echo "<title>$title</title>";
	echo "</head>";
	echo "<body $bodyvalues>";
	include('../html/gwtbody.html');
	echo "</body></html>";
} else if (function_exists($action)) {
		$action ();
} else {
	print_header_simple("",'heading', 'Mercurius');
	error("Invalid action: $action");
}
	
if($keyaccess) {  // reset to user before using keyaccess
	require_logout();
}
?>